using System.Text.Json;
using System.IO;
using System;

namespace MySoftLab.DapFlash.Models
{
    public class AppSettings
    {
        public string? SelectedTarget { get; set; }
        public int SelectedInterfaceIndex { get; set; }
        public int SelectedSpeedIndex { get; set; }
        public string? SelectedFilePath { get; set; }
        public string ProgramAddress { get; set; } = "0x8000000";

        private static readonly string SettingsPath = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory, 
            "settings.json"
        );

        public static AppSettings Load()
        {
            try
            {
                if (File.Exists(SettingsPath))
                {
                    var json = File.ReadAllText(SettingsPath);
                    return JsonSerializer.Deserialize<AppSettings>(json, AppJsonSerializerContext.Default.AppSettings) ?? new AppSettings();
                }
            }
            catch
            {
                // 如果加载失败，返回默认设置
            }
            return new AppSettings();
        }

        public void Save()
        {
            try
            {
                var json = JsonSerializer.Serialize(this, AppJsonSerializerContext.Default.AppSettings);
                File.WriteAllText(SettingsPath, json);
            }
            catch
            {
                // 保存失败时忽略错误
            }
        }
    }
} 